package com.hellogood.yaohuo.client.bussiness;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.client.common.CommonMessages;
import com.hellogood.yaohuo.client.common.LoginUser;
import com.hellogood.yaohuo.shared.data.Constants;
import com.hellogood.yaohuo.shared.services.OrgService;
import com.hellogood.yaohuo.shared.services.YaohuoService;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.layout.Layout;
import com.smartgwt.client.widgets.layout.VLayout;

public abstract class SearchController {
	protected SelectItem orgItem = null;
	protected DateItem startDateItem = null;
	protected DateItem endDateItem = null;
	protected SelectItem accountSelectItem = null;
	protected ButtonItem searchItem = null;

	protected ListGridField shopField = null;
	protected ListGridField codeField = null;
	protected ListGridField orgField = null;
	protected ListGridField vendorField = null;
	protected ListGridField dateField = null;
	protected ListGridField amountField = null;
	protected ListGridField costField = null;
	protected ListGridField psCostField = null;
	protected ListGridField zdUserField = null;
	protected ListGridField zdDateField = null;
	protected ListGridField rzDateField = null;
	protected ListGridField statusField = null;
	protected ListGridField remarkField = null;
	protected ListGridField[] fields = null;
	protected ListGrid listGrid = null;
	protected DynamicForm form = null;
	private Layout layout = null;

	public SearchController() {
		initData();
		initView();
	}

	protected void initData() {
		String staffCode = LoginUser.getInstance().getCurrentUser().getStaffCode();
		OrgService.Util.getInstance().getOrgMapByStaffCode(staffCode, new AsyncCallback<LinkedHashMap<String, String>>() {

			@Override
			public void onSuccess(LinkedHashMap<String, String> result) {
				if (result != null) {
					orgItem.setValueMap(result);
					orgItem.setValue("0");
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				SC.say(caught.getMessage());
			}
		});
	}

	private void initView() {
		orgItem = new SelectItem("org", "组织");
		// orgItem.setCanEdit(false);
		orgItem.setRequired(true);

		startDateItem = new DateItem("startDate", "开始日期");
		startDateItem.setDateFormatter(DateDisplayFormat.TOJAPANSHORTDATE);
		startDateItem.setUseTextField(true);
		startDateItem.setWidth(100);
		startDateItem.setRequired(true);
		endDateItem = new DateItem("endDate", "结束日期");
		endDateItem.setDateFormatter(DateDisplayFormat.TOJAPANSHORTDATE);
		endDateItem.setUseTextField(true);
		endDateItem.setWidth(100);
		endDateItem.setRequired(true);
		Date date = new Date();
		endDateItem.setValue(date);
		date.setDate(1);
		startDateItem.setValue(date);
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put(Constants.RUZHANG_CODE_ALL, Constants.RUZHANG_NAME_ALL);
		map.put(Constants.RUZHANG_CODE_NO, Constants.RUZHANG_NAME_NO);
		map.put(Constants.RUZHANG_CODE_YES, Constants.RUZHANG_NAME_YES);
		accountSelectItem = new SelectItem("account", "选择");
		accountSelectItem.setWidth(100);
		accountSelectItem.setValueMap(map);
		accountSelectItem.setValue("all");

		searchItem = new ButtonItem("search", "查询");
		searchItem.setStartRow(false);
		searchItem.addClickHandler(new SearchClickHandler());

		form = new DynamicForm();
		form.setSize("100%", "10%");
		form.setNumCols(14);

		buildFormFields();

		codeField = new ListGridField("code", "单号");
		shopField = new ListGridField("shop", "门店");
		orgField = new ListGridField("org", "组织");
		orgField.setWidth("15%");
		vendorField = new ListGridField("vendor", "供应商");
		dateField = new ListGridField("date", "制单日期");
		amountField = new ListGridField("amount", "数量");
		amountField.setWidth("5%");
		amountField.setAlign(Alignment.RIGHT);
		costField = new ListGridField("cost", "进价金额");
		costField.setCellFormatter(new CellFormatter() {  
            public String format(Object value, ListGridRecord record, int rowNum, int colNum) {  
                if(value == null) return null;  
                NumberFormat nf = NumberFormat.getFormat("#,##0.00");  
                try {  
                    return nf.format(((Number)value).floatValue());  
                } catch (Exception e) {  
                    return value.toString();  
                }  
            }  
        });  
		
		psCostField = new ListGridField("PsCost", "配送金额");
		psCostField.setCellFormatter(new CellFormatter() {  
            public String format(Object value, ListGridRecord record, int rowNum, int colNum) {  
                if(value == null) return null;  
                NumberFormat nf = NumberFormat.getFormat("#,##0.00");  
                try {  
                    return nf.format(((Number)value).floatValue());  
                } catch (Exception e) {  
                    return value.toString();  
                }  
            }  
        });  
		
		psCostField.setAlign(Alignment.RIGHT);
		zdUserField = new ListGridField("zdUser", "制单人");
		zdDateField = new ListGridField("zdDate", "制单日期");
		rzDateField = new ListGridField("rzDate", "入账日期");
		statusField = new ListGridField("status", "状态");
		remarkField = new ListGridField("remark", "备注");

		buildListFields();

		listGrid = new ListGrid();
		listGrid.setFields(fields);
		listGrid.setMargin(2);
		listGrid.setSize("100%", "90%");
		listGrid.addSelectionChangedHandler(new SelectionChangedHandler() {

			@Override
			public void onSelectionChanged(SelectionEvent event) {
				Record r = event.getSelectedRecord();
				if (r != null) {
					String rzDate = r.getAttribute("rzDate");
					if (rzDate != null && !rzDate.equals("")) {

					}
				}
			}
		});

		layout = new VLayout();
		layout.setSize("100%", "100%");
		layout.setMembers(form, listGrid);
	}

	protected void buildFormFields() {
		form.setFields(orgItem, startDateItem, endDateItem, accountSelectItem, searchItem);
	}

	protected void buildListFields() {
		fields = new ListGridField[] { codeField, orgField, dateField, amountField, costField,zdUserField, zdDateField, rzDateField, remarkField };
	}

	public Canvas getCanvas() {
		return layout;
	}

	public ListGrid getListGrid() {
		return listGrid;
	}

	private class SearchClickHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			if (form.validate()) {
				String orgCode = "0";
				String startDate = startDateItem.getDisplayValue().toString();
				String endDate = endDateItem.getDisplayValue().toString();
				if (orgItem.getValue() != null) {
					orgCode = orgItem.getValue().toString().split("-")[0];
				}
				String rz = accountSelectItem.getValue().toString();
				searchForm(orgCode, startDate, endDate, rz);
			}
		}
	}

	abstract public void searchForm(String orgCode, String startDate, String endDate, String rz);
	
	public void bankForm(){
		ListGridRecord record = listGrid.getSelectedRecord();
		if (record != null) {
			String code = record.getAttribute("code");
			List<String> list = new ArrayList<String>();
			if(code!=null){
			list.add(code.toString());
			YaohuoService.Util.getInstance().bankForm(list, new AsyncCallback<String>() {

				@Override
				public void onSuccess(String result) {
					if (!result.equals("")) {
						SC.say(result);
					} else {
						SC.say(CommonMessages.BankSuccess);
					}
				}

				@Override
				public void onFailure(Throwable caught) {
					SC.say(caught.getMessage());
				}
			});
			}
		}
	}

}
